package com.isunland.managesystem.ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.widget.ArrayAdapter;
import com.isunland.managesystem.base.BaseFragment;
import com.isunland.managesystem.entity.BaseParams;
import com.isunland.managesystem.entity.ZTreeNode;
import com.isunland.managesystem.utils.MyStringUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.SharedPreferencesUtil;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

/**
 * 对象功能:
 * 开发公司: 北京信普达系统工程有限公司
 * 开发人员: wangyanan
 * 创建时间: 2017/6/3 14:46
 */
public class SelectActivityDialogFragment extends BaseDialogFragment {
  public static final String EMPTY = "无";
  private ArrayAdapter<String> mAdapter;

  @Override public void initData() {
    super.initData();
    ArrayList<String> mList = new ArrayList<>();
    mList.add(EMPTY);
    ArrayList<String> nameArr = MyUtils.getActivitiesName(mActivity);
    if (nameArr == null || nameArr.size() == 0) return;
    Collections.sort(nameArr, new Comparator<String>() {
      public int compare(String mapping1, String mapping2) {
        return mapping1.compareTo(mapping2);
      }
    });
    mList.addAll(nameArr);
    mAdapter = new ArrayAdapter<>(mActivity, android.R.layout.select_dialog_singlechoice, mList);
  }

  @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) {
    super.onCreateDialog(savedInstanceState);
    return new AlertDialog.Builder(mActivity).setTitle("选择Activity")
        .setAdapter(mAdapter, new DialogInterface.OnClickListener() {
          @Override public void onClick(DialogInterface dialog, int which) {
            String strName = mAdapter.getItem(which);
            if (getTargetFragment() == null || MyStringUtil.isEmpty(strName)) return;
            Intent i = new Intent();
            BaseParams<ZTreeNode> params = new BaseParams<>();
            params.setTitle(strName);
            i.putExtra(BaseFragment.EXTRA_PARAMS, params);
            getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, i);

            SharedPreferencesUtil.setString(mActivity, SharedPreferencesUtil.KEY_LAUNCH_ACTIVITY,
                MyStringUtil.equals(EMPTY, strName) ? "" : strName);
          }
        })
        .create();
  }
}
